package com.zat.mes.andrmes.dofun.work

import android.Manifest
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.media.RingtoneManager
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.KeyEvent
import android.view.View
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.google.gson.JsonObject
import com.zat.mes.andrmes.R
import com.zat.mes.andrmes.base.BaseActivity
import com.zat.mes.andrmes.customerview.BottomSignDailog
import com.zat.mes.andrmes.data.PackBean
import com.zat.mes.andrmes.data.ParantTypeItem
import com.zat.mes.andrmes.dofun.QrScanActivity
import com.zat.mes.andrmes.dofun.qualitytest.vm.QcPlanViewModel
import com.zat.mes.andrmes.dofun.work.vm.HouseModel
import com.zat.mes.andrmes.global.CompanionCode
import com.zat.mes.andrmes.global.CompanionType
import com.zat.mes.andrmes.utils.ReadCardUtils
import com.zat.mes.andrmes.utils.SystemActivityUtil
import com.zat.mes.andrmes.utils.showToast
import kotlinx.android.synthetic.main.activity_in_house.*
import kotlinx.android.synthetic.main.activity_yarn_in.*
import kotlinx.android.synthetic.main.layout_title.*
import org.json.JSONObject
import permissions.dispatcher.*

/**
 * 现场仓 入库
 */
@RuntimePermissions
class InHouseActivity : BaseActivity() {

    //U口读卡器,类似于外接键盘
    private var readCardUtils: ReadCardUtils? = null
    //仓库类型
    var house: MutableList<ParantTypeItem>? = null
    var qcModel: QcPlanViewModel? = null
    var houseModel: HouseModel? = null
    var packBean: PackBean? = null
    override fun init() {
        initView()
        initData()
    }

    private fun initView() {
        setContentView(R.layout.activity_in_house)
        tVtitle.text = "入库"
        rlReturnTitle.visibility = View.VISIBLE
        rlReturnTitle.setOnClickListener { finish() }
        llHouseInhouse.setOnClickListener {
            showBottomDialog(house)
        }
        btnScanInhouse.setOnClickListener {
            showCameraWithPermissionCheck()
        }
        btnInhouse.setOnClickListener {
            if (tvHouseInhouse.getTag(tvHouseInhouse.id) == null) {
                showToast("请选择仓库")
                return@setOnClickListener
            }
            val typeItem = tvHouseInhouse.getTag(tvHouseInhouse.id) as ParantTypeItem
            if (packBean == null) {
                showToast("请先扫码或刷卡")
                return@setOnClickListener
            }
            if (TextUtils.isEmpty(etAPInhouse.text.toString())){
                showToast("请输入A品数量")
                return@setOnClickListener
            }
            if (TextUtils.isEmpty(etBPInhouse.text.toString())){
                showToast("请输入B品数量")
                return@setOnClickListener
            }
            val jsonObject = JSONObject()
            jsonObject.put("packId", packBean?.packId)
            jsonObject.put("storageType", typeItem.typecode)
            jsonObject.put("remarks1",etAPInhouse.text.toString())
            jsonObject.put("remarks2",etBPInhouse.text.toString())
            showLoading()
            houseModel?.loadInhouseSave(jsonObject.toString())
        }

    }

    private fun initData() {
//读卡器声明
        readCardUtils = ReadCardUtils()
        initCardReader()

        qcModel = ViewModelProvider(this).get(QcPlanViewModel::class.java)
        qcModel?.getParantTypeData()?.observe(this, Observer {
            closeLoading()
            house = it.get("WAREHOUSE_STORAGE")
        })
        qcModel?.loadParantTypeList("WAREHOUSE_STORAGE")

        houseModel = ViewModelProvider(this).get(HouseModel::class.java)
        houseModel?.getPackData()?.observe(this, Observer {
            closeLoading()
            packBean = it
            tvPackNumInHouse.text ="包号："+ packBean?.packNO+"；数量："+packBean?.quantity

        })
        houseModel?.getPostData()?.observe(this, Observer {
            closeLoading()
            showToast(it)
        })

    }

    /**
     * 初始化刷卡器
     */
    private fun initCardReader() {

        readCardUtils?.setReadSuccessListener(ReadCardUtils.OnReadSuccessListener() {
            Log.e("zhangyucode", "barcode: " + it);
            if (it.length == 8 || it.length == 10) {
                //叫唤
                val notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
                val r = RingtoneManager.getRingtone(applicationContext, notification)
                r.play()
//                val soundPool = SoundPool(2, AudioManager.STREAM_MUSIC, 0)
//                soundPool.load(this,R.raw.ondo,1)
//                soundPool.play(1,1f, 1f, 0, 0, 1f);
                showLoading()
                houseModel?.loadPackDataByRFRD(it)
            }
        })

    }

    /**
     * 设备刷卡监听
     */
    override fun dispatchKeyEvent(event: KeyEvent?): Boolean {
        if (ReadCardUtils.isInputFromReader(this, event)) {
            if (readCardUtils != null) {
                readCardUtils?.resolveKeyEvent(event);
            }
        }
        return super.dispatchKeyEvent(event);

    }

    override fun onDestroy() {
        readCardUtils?.removeScanSuccessListener();
        readCardUtils = null;
        super.onDestroy()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        val qrCode = data?.getStringExtra(CompanionType.INTENT_EXTRA_QRCODE)
        if (resultCode == Activity.RESULT_OK) {
            //根据二维码查包
            showLoading()
            houseModel?.loadPackData(qrCode)
        }
    }


    /**
     * 显示底部弹框 处理方式
     */
    fun showBottomDialog(list: MutableList<ParantTypeItem>?) {
        BottomSignDailog(this, list, object : BottomSignDailog.OnBottomSelectListener {
            override fun onBottomSelect(parantTypeItem: ParantTypeItem) {
                tvHouseInhouse.text = parantTypeItem.typename
                tvHouseInhouse.setTag(tvHouseInhouse.id, parantTypeItem)

            }

        })
    }

    @NeedsPermission(Manifest.permission.CAMERA)
    fun showCamera() {
        try {
            startActivityForResult(
                Intent(this, QrScanActivity::class.java),
                CompanionCode.REQUESTCODE
            )
        } catch (e: Exception) {
            Log.e("activity", e.toString())
        }
    }

    @OnShowRationale(Manifest.permission.CAMERA)
    fun showRationaleForCamera(request: PermissionRequest) {
        request.proceed();
        Log.e("permission", "OnShowRationale")
    }

    @OnPermissionDenied(Manifest.permission.CAMERA)
    fun onCameraDenied() {
        showCameraWithPermissionCheck()
    }

    @OnNeverAskAgain(Manifest.permission.CAMERA)
    fun onCameraNeverAskAgain() {
//        showToast("请到设置打开相机权限")
        SystemActivityUtil.getAppDetailSettingIntent(this)
    }

    @SuppressLint("NeedOnRequestPermissionsResult")
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        onRequestPermissionsResult(requestCode, grantResults)

    }
}
